#coding=utf-8
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404, HttpResponse
from job.models import Job, Company
from office.models import Office
from pub.views import _app_page


_tmpl_index = "job/index.html"
_tmpl_job_detail = "job/detail.html"
_tmpl_company_detail = "job/company_detail.html"
model_url = "/job/" #为模板中的区域选择的链接拼接完整URL路径

def index(request, dist_id=None):
    '''工作首页'''
    if dist_id is None:
        dist_id = -1
        offices = Office.objects.filter(city = request.session["city"], )
    else:
        offices = Office.objects.filter(city=request.session["city"], district_id = dist_id)
    companies = Company.objects.filter(office__in = offices)
    jobList = Job.objects.filter(company__in = companies).order_by("end_date")
    count = jobList.count()
    paginator = Paginator(jobList, 10)
    if request.GET.get('page'):
        current_page = int(request.GET.get('page'))
    else:
        current_page = 1
    try:
        jobList = paginator.page(current_page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        jobList = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        jobList = paginator.page(paginator.num_pages)
    local = dict(jobList=jobList, model_url=model_url, count=count, districts_select=int(dist_id))
    return _app_page(_tmpl_index, request, local)

def job_detail(request, job_id=None):
    '''工作详情页面
    job_id : 工作ID
    '''
    if job_id is None:
        raise Http404
    try:
        job = Job.objects.select_related().get(id=job_id)
    except Exception:
        #TODO:需要新建转到错误提示页面
        raise Http404
    jobsInCompany = Job.objects.filter(company=job.company).exclude(id=job.id).order_by("end_date")[0:8]
    local = dict(job=job, model_url=model_url, jobsInCompany=jobsInCompany)
    return _app_page(_tmpl_job_detail, request, local)

def company_detail(request, company_id=None):
    '''公司详情页面'''
    if company_id is None:
        raise Http404
    try:
        company = Company.objects.get(id=company_id)
    except Exception:
        raise Http404
    jobsInCompany = Job.objects.filter(company=company).order_by("end_date")
    local = dict(company=company, model_url=model_url, jobsInCompany=jobsInCompany)
    return _app_page(_tmpl_company_detail, request, local)
